// pages/index/index.js
const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'),
    categories: [],
    hotDishes: [],
    banners: [
      {
        id: 1,
        image: '/images/banner1.jpg',
        title: '美味佳肴'
      },
      {
        id: 2,
        image: '/images/banner2.jpg',
        title: '新鲜食材'
      }
    ]
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    this.loadCategories()
    this.loadHotDishes()
  },

  // 加载分类数据
  loadCategories() {
    wx.request({
      url: `${app.globalData.baseUrl}/mini/category/list`,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            categories: res.data.data || []
          })
        }
      },
      fail: (err) => {
        console.error('加载分类失败', err)
      }
    })
  },

  // 加载热门菜品
  loadHotDishes() {
    wx.request({
      url: `${app.globalData.baseUrl}/mini/dish/hot`,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 1) {
          this.setData({
            hotDishes: res.data.data || []
          })
        }
      },
      fail: (err) => {
        console.error('加载热门菜品失败', err)
      }
    })
  },

  // 跳转到菜单页面
  goToMenu() {
    wx.switchTab({
      url: '/pages/menu/menu'
    })
  },

  // 跳转到分类菜品
  goToCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/menu/menu?categoryId=${categoryId}`
    })
  },

  // 跳转到菜品详情
  goToDishDetail(e) {
    const dishId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/dish/detail?id=${dishId}`
    })
  },

  // 轮播图点击
  onBannerTap(e) {
    const index = e.detail.current
    console.log('轮播图点击', index)
  },

  getUserProfile(e) {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

  getUserInfo(e) {
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})